import Taro from '@tarojs/taro'
import storage from './storage'
import { getDictDataList, getDictData } from '@/network/apis'


const IMAGE_SERVERURL = 'https://xjs001.oss-cn-hangzhou.aliyuncs.com' // 旧
const IMAGE_SERVER_URL = 'https://platform-icon.oss-cn-hangzhou.aliyuncs.com' // 新

const debounce = (fn, delay) => {
  let timerId;

  return function () {
    const context = this;
    const args = arguments;

    clearTimeout(timerId);
    timerId = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
};

const image2Path = (name, scope) => {
  return name && name.indexOf('http') != -1 ? name : `${IMAGE_SERVERURL}/${storage.get('manufacturerId')}/${scope}/${name}`;
}

const getMiniProgramEnv = () => {
  const env = Taro.getAccountInfoSync().miniProgram.envVersion
  console.log("env:===========>:", env)
  return env
}

const getDicts = (dictTypes) => {
  return new Promise(async (resolve, reject) => {
    const { data } = await getDictDataList(dictTypes);

    const dicts = {};

    dictTypes.forEach(type => {
      const dictListItem = data[type].map(item => {
        if (item.remark) {
          try {
            item.remark = JSON.parse(item.remark);
          } catch (error) {
            item.remark = {};
          }
        }

        return {
          ...item,
          text: item.dictLabel,
          label: item.dictLabel,
          value: item.dictValue,
          color: item.remark?.color || '',
          background: item.remark?.background || ''
        };
      });

      dicts[type] = dictListItem;
    });

    resolve(dicts);
  });
};

const getDict = (dictType) => {
  return new Promise(async (resolve, reject) => {
    const { data } = await getDictData({ dictType: dictType });

    const dictData = data.records?.length
      ? data.records.map(item => {
          // 判断item.remark是否为json
          if (item.remark) {
            try {
              item.remark = JSON.parse(item.remark);
            } catch (error) {
              item.remark = {};
            }
          }

          return {
            ...item,
            text: item.dictLabel,
            label: item.dictLabel,
            value: item.dictValue,
            color: item.remark?.color || '',
            background: item.remark?.background || ''
          };
        })
      : [];

    resolve(dictData);
  });
}

const getFileType = (filename) => {
  if (!filename) return '';

  // 定义文件的类型
  let fileType = filename.substr(filename.lastIndexOf('.') + 1)
  // 转换字符串为小写
  fileType = fileType.toLowerCase()
  // 判断图片
  if (['bmp', 'jpg', 'jpeg', 'png', 'gif'].indexOf(fileType) !== -1) {
    fileType = 'image'
  }
  // 判断视频
  if (['m3u8', 'ts', 'mp4', '3gp', 'asf', 'wmv', 'avi', 'mkv', 'rmvb', 'flv', 'mp3', 'ogg', 'amr', 'mov', 'video'].indexOf(fileType) !== -1) {
    fileType = 'video'
  }

  // 判断音频
  if (['aac', 'ac3', 'mp3', 'mp3adu', 'mp3adufloat', 'mp3float', 'mp3on4', 'mp3on4float', 'amrnb', 'amrwb', 'cook', 'ra_144', 'ra_288', 'sipr', 'wmav1', 'wmav2', 'wmavoice', 'wmapro', 'wamlossless', 'nellymoser', 'vorbis'].indexOf(fileType) !== -1) {
    fileType = 'audio'
  }
  // 判断文档
  if (['pdf', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx'].indexOf(fileType) !== -1) {
    fileType = 'document'
  }

  // 判断压缩格式
  if (['zip', '7z', 'rar', 'apz', 'ar', 'bz', 'car', 'dar', 'cpgz', 'f', 'ha', 'hbc', 'hbc2', 'hbe', 'hpk', 'hyp'].indexOf(fileType) !== -1) {
    fileType = 'compress'
    console.log('压缩格式:', fileType)
  }
  return fileType
}

const common = {
  IMAGE_SERVERURL,
  IMAGE_SERVER_URL,
  debounce,
  image2Path,
  getMiniProgramEnv,
  getDicts,
  getDict,
  getFileType
};

export default common